from datetime import datetime
import pickle

from django.views.generic.simple import direct_to_template
from django.contrib.auth.models import User
from django.shortcuts import redirect
from django.shortcuts import get_object_or_404
from django.contrib.auth import login
from craft_life.utils import key_gen, captcha_check

from forms import RegistrationForm
from models import UserProfile


def registration(request):
    captcha_key = key_gen()
    form = RegistrationForm(request.POST or None, initial={'captcha': captcha_key})
    if form.is_valid() and captcha_check(request):
        user = User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password'])
        user.save()
        user.userprofile = UserProfile.objects.create(user)
        user.is_active = False
        user.save()
        request.session['captcha'] = captcha_key
        return redirect('uac.views.activation_request', id=user.id)
    elif not captcha_check(request):
        pass

    request.session['captcha'] = captcha_key
    return direct_to_template(request, 'uac/registration.html', {'form': form, 'captcha': request.session['captcha']})

def activation_request(request, id):
    user = get_object_or_404(User, id=id)
    # delta = datetime.now() - user.get_profile().last_activation
    errors = []
    # if delta.seconds < 60*30:
        # errors.append('time')

    if not errors:
        key = key_gen()
        user.get_profile().activation_key = key
        user.get_profile().save()
        # sendmail
        return direct_to_template(request, 'uac/activation_process.html', {'errors': ['key_sended', key]})
    else:
        return direct_to_template(request, 'uac/activation_process.html', {'errors': errors})

def activation_process(request, id, key):
    user = get_object_or_404(User, id=id)
    # delta = datetime.now() - user.get_profile().last_activation
    if user.get_profile().activation_key != key:
        return direct_to_template(request, 'uac/activation_process.html', {'error': 'invalid_key'})
    # if delta.seconds < 60*120:
    #     return direct_to_template(request, 'uac/activation_process.html', {'error': 'key_expired'})

    user.is_active = True
    user.save()
    login(request, user)
    return direct_to_template(request, 'uac/activation_process.html')

def show_profile(request, id):
    user = get_object_or_404(User, id=id)
    return direct_to_template(request, 'uac/profile.html', {'u': user})

def control_profile(request):
    ad = pickle.loads(request.user.get_profile().additional_data)
    if request.method == "POST":
        for k in [key for key in request.POST.keys() if key.startswith('ad_')]:
            ad[k[3:]] = request.POST[k]
        request.user.get_profile().additional_data = pickle.dumps(ad)
        request.user.get_profile().save()

    return direct_to_template(request, 'uac/control_profile.html', {'ad': ad, 'ad_select': request.user.get_profile().AD_SELECT})
